package com.example.mangroves.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class ImageUploadController {

    private static final String DIRECTORY = "C:\\Users\\26498\\IdeaProjects\\Mangroves\\src\\main\\resources\\static\\camera_img";

    @PostMapping("/upload-image")
    public ResponseEntity<String> uploadImage(@RequestParam("camera_id") String cameraId,
                                              @RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST);
        }

        try {
            // 保存图片至本地
            byte[] bytes = file.getBytes();
            Path path = Paths.get(DIRECTORY + File.separator + cameraId + "_" + file.getOriginalFilename());

            System.out.println("Attempting to write file: " + path.toString());
            Files.write(path, bytes);
            System.out.println("File written successfully.");

            // 按要求输出图片
            System.out.println("Received file: " + file.getOriginalFilename() + " from camera ID: " + cameraId);
        } catch (IOException e) {
            return new ResponseEntity<>("Error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new ResponseEntity<>("OK", HttpStatus.OK);
    }
}
